#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from twisted.internet import task
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class DatabaseSyncService:
    def __init__(self, game_state, interval=60):  # 默认每60秒同步一次
        self.game_state = game_state
        self.interval = interval
        self.sync_task = None

    def start_sync(self):
        """开始定期同步"""
        self.sync_task = task.LoopingCall(self.sync_data)
        self.sync_task.start(self.interval)
        logging.info(f"数据库同步服务已启动，同步间隔: {self.interval}秒")

    def stop_sync(self):
        """停止定期同步"""
        if self.sync_task and self.sync_task.running:
            self.sync_task.stop()
            logging.info("数据库同步服务已停止")

    def sync_data(self):
        """同步数据到数据库"""
        try:
            success_count = self.game_state.sync_all_users_to_db()
            logging.info(f"数据同步完成，成功同步 {success_count} 个玩家数据")
        except Exception as e:
            logging.error(f"数据同步失败: {e}")
